package cn.wolfcode.common.web.resolver;

import cn.wolfcode.common.anno.RequestUser;
import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.redis.CommonRedisKey;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 用户参数解析器
 */
public class UserInfoMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private final StringRedisTemplate redisTemplate;

    public UserInfoMethodArgumentResolver(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //判断是否需要解析该参数，如果需要则执行resolveArgument方法
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //要解析的参数： 贴有 @RequestUser 注解，并且该参数类型是 UserInfo
        return parameter.hasParameterAnnotation(RequestUser.class) &&
                parameter.getParameterType() == UserInfo.class;
    }

    //给解析的参数设置值
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader(CommonConstants.TOKEN_NAME);
        return JSON.parseObject(redisTemplate.opsForValue().get(CommonRedisKey.USER_TOKEN.getRealKey(token)), UserInfo.class);
    }
}
